import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:tv_friso_screen/TV/home_page_tv.dart';
import 'package:tv_friso_screen/TV/sales_en_page_tv.dart';
import 'package:tv_friso_screen/TV/sales_page_tv.dart';
import 'package:tv_friso_screen/TV/store_en_page_tv.dart';
import 'package:tv_friso_screen/TV/store_page_tv.dart';
import 'package:tv_friso_screen/login_tv_page.dart';
import 'package:tv_friso_screen/utils/phone_info_utils.dart';

import '../utils/share_pre_utils.dart';
import 'home_en_page_tv.dart';

//店主 主导页
class HomeMainPageTV extends StatefulWidget {
  const HomeMainPageTV({super.key});

  // final TabsBar tabBar;

  // const HomeMainPage({Key? key, required this.tabBar}) : super(key: key);

  @override
  State<HomeMainPageTV> createState() => _HomeMainPageState();
}

class _HomeMainPageState extends State<HomeMainPageTV>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  int _currentIndex = 0;
  double _dragStartPosition = 0.0;
  FocusNode focusNodeLoginOut = FocusNode();
  FocusNode focusNodeGoLeft = FocusNode();
  FocusNode focusNodeGoRight = FocusNode();

  List<Widget> _pageList = [
    const HomePageTV(),
    const SalesPageTV(),
    const StorePageTV(),
  ];

  final pageController = PageController();

  Timer? downTimer; //右上角时分秒显示倒计时
  var nowTime = "";
  var currentLanguage = '';

  // 添加中文和英文按钮的焦点节点
  FocusNode focusNodeChinese = FocusNode();
  FocusNode focusNodeEnglish = FocusNode();

  void countDownTimer() {
    downTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      //每隔 1 秒钟 刷新一次时分秒
      setState(() {
        nowTime = PhoneInfoUtils.getTime();
      });
    });
  }

  @override
  void initState() {
    super.initState();
    countDownTimer();
    currentLanguage = SharePreUtils.getLanguage();
    if (currentLanguage == "zh") {
      _pageList = [
        const HomePageTV(),
        const SalesPageTV(),
        const StorePageTV(),
      ];
    } else {
      _pageList = [
        const HomeEnPageTV(),
        const SalesEnPageTV(),
        const StoreEnPageTV(),
      ];
    }
    focusNodeLoginOut = FocusNode();

    // 初始化焦点节点
    focusNodeChinese = FocusNode();
    focusNodeEnglish = FocusNode();

    // 设置退出登录按钮初始焦点
    focusNodeLoginOut.requestFocus();
  }

  @override
  void dispose() {
    super.dispose();
    downTimer?.cancel();
    focusNodeLoginOut.dispose();
    focusNodeChinese.dispose();
    focusNodeEnglish.dispose();
  }

  //当PageView可滑动时 会调用这个方法
  void onPageChanged(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用super.build(context)
    return Scaffold(
      body: Stack(
        children: [
          GestureDetector(
            onHorizontalDragStart: (details) {
              _dragStartPosition = details.localPosition.dx; // 记录起始位置
            },
            onHorizontalDragEnd: (details) {
              double dragDistance =
                  details.velocity.pixelsPerSecond.dx; // 获取滑动距离
              // 设置滑动阈值
              if (dragDistance > 10) {
                // 向右滑动，切换到上一页
                pageController.previousPage(
                  duration: const Duration(milliseconds: 300),
                  curve: Curves.easeInOut,
                );
              } else if (dragDistance < -10) {
                // 向左滑动，切换到下一页
                pageController.nextPage(
                  duration: const Duration(milliseconds: 300),
                  curve: Curves.easeInOut,
                );
              }
            },
            child: PageView(
              controller: pageController,
              // onPageChanged: onPageChanged,
              physics: const NeverScrollableScrollPhysics(), //禁止滑动
              // physics: const AlwaysScrollableScrollPhysics(),
              children: _pageList,
            ),
          ),
          Focus(
            focusNode: focusNodeLoginOut,
            onKey: (node, event) {
              if (event is RawKeyDownEvent) {
                if (event.logicalKey == LogicalKeyboardKey.select) {
                  _handleLogout(context);
                  return KeyEventResult.handled;
                }
                if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
                  focusNodeChinese.requestFocus();
                  return KeyEventResult.handled;
                }
              }
              return KeyEventResult.ignored;
            },
            child: GestureDetector(
              onTap: () => _handleLogout(context),
              child: Container(
                margin: EdgeInsets.only(top: 6.w, left: 20.w),
                child: Container(
                  padding: EdgeInsets.only(
                      left: 20.w, right: 20.w, top: 10.w, bottom: 10.w),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.w),
                    border: Border.all(
                      color: focusNodeLoginOut.hasFocus
                          ? Colors.red
                          : const Color(0xFF829EEE),
                      width: 1.w,
                    ),
                  ),
                  child: Text(
                    currentLanguage == "zh" ? "退出登录" : "Log out",
                    style: TextStyle(
                      color: const Color(0xFF1ED2FF),
                      fontSize: 26.sp,
                      fontWeight: FontWeight.normal,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
              ),
            ),
          ),

          Positioned(
            left: 180.w,
            top: 5.w,
            child: Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.w),
                  border: Border.all(
                    color: const Color.fromRGBO(3, 90, 168, 1),
                    width: 1.w, // 边框宽度
                  )),
              child: Row(
                children: [
                  Focus(
                    focusNode: focusNodeChinese,
                    onKey: (node, event) {
                      if (event is RawKeyDownEvent) {
                        if (event.logicalKey == LogicalKeyboardKey.select) {
                          setState(() {
                            currentLanguage = "zh";
                            SharePreUtils.setLanguage(currentLanguage);
                            _pageList = [
                              const HomePageTV(),
                              const SalesPageTV(),
                              const StorePageTV(),
                            ];
                          });
                          return KeyEventResult.handled;
                        }
                        if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
                          focusNodeLoginOut.requestFocus();
                          return KeyEventResult.handled;
                        }
                        if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
                          focusNodeEnglish.requestFocus();
                          return KeyEventResult.handled;
                        }
                      }
                      return KeyEventResult.ignored;
                    },
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          currentLanguage = "zh";
                          SharePreUtils.setLanguage(currentLanguage);
                          _pageList = [
                            const HomePageTV(),
                            const SalesPageTV(),
                            const StorePageTV(),
                          ];
                        });
                      },
                      child: Container(
                        width: 150.w,
                        height: 55.w,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8.w),
                          border: Border.all(
                            color: focusNodeChinese.hasFocus
                                ? Colors.red
                                : Colors.transparent,
                            width: 1.w,
                          ),
                          color: currentLanguage == "zh"
                              ? const Color.fromRGBO(30, 210, 255, 1)
                              : Colors.transparent,
                        ),
                        padding: EdgeInsets.only(top: 8.w, bottom: 8.w),
                        child: Text(
                          "中文",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: currentLanguage == "zh"
                                ? const Color.fromRGBO(8, 42, 51, 1)
                                : const Color.fromRGBO(30, 210, 255, 1),
                            fontSize: 28.sp,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                    ),
                  ),
                  Focus(
                    focusNode: focusNodeEnglish,
                    onKey: (node, event) {
                      if (event is RawKeyDownEvent) {
                        if (event.logicalKey == LogicalKeyboardKey.select) {
                          setState(() {
                            currentLanguage = "en";
                            SharePreUtils.setLanguage(currentLanguage);
                            _pageList = [
                              const HomeEnPageTV(),
                              const SalesEnPageTV(),
                              const StoreEnPageTV(),
                            ];
                          });
                          return KeyEventResult.handled;
                        }
                        if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
                          focusNodeChinese.requestFocus();
                          return KeyEventResult.handled;
                        }
                      }
                      return KeyEventResult.ignored;
                    },
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          currentLanguage = "en";
                          SharePreUtils.setLanguage(currentLanguage);
                          _pageList = [
                            const HomeEnPageTV(),
                            const SalesEnPageTV(),
                            const StoreEnPageTV(),
                          ];
                        });
                      },
                      child: Container(
                        width: 150.w,
                        height: 55.w,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8.w),
                          border: Border.all(
                            color: focusNodeEnglish.hasFocus
                                ? Colors.red
                                : Colors.transparent,
                            width: 1.w,
                          ),
                          color: currentLanguage == "en"
                              ? const Color.fromRGBO(30, 210, 255, 1)
                              : Colors.transparent,
                        ),
                        padding: EdgeInsets.only(top: 8.w, bottom: 8.w),
                        child: Text(
                          "English",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: currentLanguage == "en"
                                ? const Color.fromRGBO(8, 42, 51, 1)
                                : const Color.fromRGBO(30, 210, 255, 1),
                            fontSize: 28.sp,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),

          // Positioned(
          //     left: 0,
          //     top: MediaQuery.of(context).size.height / 2 - 50.w,
          //     child: InkWell(
          //       focusNode: focusNodeGoLeft,
          //       onTap: () {
          //         pageController.previousPage(
          //           duration: const Duration(milliseconds: 300),
          //           curve: Curves.easeInOut,
          //         );
          //       },
          //       child: Icon(
          //         Icons.arrow_back_ios_new,
          //         size: 50.w,
          //         color: Colors.white,
          //       ),
          //     )),
          // Positioned(
          //     right: 0,
          //     top: MediaQuery.of(context).size.height / 2 - 50.w,
          //     child: InkWell(
          //       focusNode: focusNodeGoRight,
          //       onTap: () {
          //         pageController.nextPage(
          //           duration: const Duration(milliseconds: 300),
          //           curve: Curves.easeInOut,
          //         );
          //       },
          //       child: Icon(
          //         Icons.arrow_forward_ios_rounded,
          //         size: 50.w,
          //         color: Colors.white,
          //       ),
          //     )),
          Container(
            padding: EdgeInsets.only(top: 20.w, right: 20.w),
            height: 100.w,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  nowTime,
                  style: TextStyle(
                    color: const Color(0xFFBDE1FF),
                    fontSize: 28.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(
                  width: 20.w,
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      getWeekDay(),
                      style: TextStyle(
                        color: const Color(0xFFBDE1FF),
                        fontSize: 24.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      PhoneInfoUtils.getDate(),
                      style: TextStyle(
                        color: const Color(0xFFBDE1FF),
                        fontSize: 24.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _handleLogout(BuildContext context) async {
    await SharePreUtils.setToken("");
    if (!mounted) return;

    Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (context) => const LoginTVPage()),
        (route) => false);
  }

  void showLoginOutDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Stack(
                children: [
                  Container(
                    alignment: Alignment.center,
                    width: 500.w,
                    height: 500.w,
                    margin: EdgeInsets.only(
                      left: 65.w,
                      right: 65.w,
                      top: 70.w,
                    ),
                    padding: EdgeInsets.only(left: 40.w, right: 40.w),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(20.w)),
                      image: const DecorationImage(
                        image: AssetImage("assets/images/icon_update_bg.png"),
                        fit: BoxFit.fill,
                      ),
                    ),
                    child: Column(
                      // crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          height: 60.w,
                        ),
                        Text(
                          currentLanguage == "zh" ? "退出登录" : "Log out",
                          style: TextStyle(
                            fontSize: 32.sp,
                            color: const Color(0xFF00EEFF),
                            fontWeight: FontWeight.bold,
                            decoration: TextDecoration.none,
                          ),
                          textAlign: TextAlign.center,
                        ),
                        SizedBox(
                          height: 20.h,
                        ),
                        Text(
                          currentLanguage == "zh"
                              ? "确定要退出登录吗?"
                              : "Are you sure you want to log out?",
                          softWrap: true,
                          style: TextStyle(
                            fontSize: 24.sp,
                            color: const Color(0xff8BD8DD),
                            decoration: TextDecoration.none,
                            fontWeight: FontWeight.normal,
                          ),
                          textAlign: TextAlign.start,
                        ),
                        const Spacer(),
                        Container(
                          margin: EdgeInsets.only(
                              left: 20.w, right: 20.w, bottom: 60.w),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  //回到登录页
                                  SharePreUtils.setToken("");
                                  Navigator.of(context).pushAndRemoveUntil(
                                      MaterialPageRoute(
                                          builder: (context) =>
                                              const LoginTVPage()),
                                      (route) => false);
                                },
                                child: Container(
                                  padding: EdgeInsets.only(
                                      left: 40.w,
                                      right: 40.w,
                                      top: 20.w,
                                      bottom: 20.w),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                    // borderRadius:
                                    //     BorderRadius.all(Radius.circular(20.w)),
                                    image: DecorationImage(
                                      image: AssetImage(
                                          "assets/images/icon_update_btn.png"),
                                      fit: BoxFit.fill,
                                    ),
                                  ),
                                  child: Text(
                                    currentLanguage == "zh" ? "确定" : "OK",
                                    style: TextStyle(
                                      fontSize: 28.sp,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                      decoration: TextDecoration.none,
                                    ),
                                  ),
                                ),
                              ),
                              GestureDetector(
                                onTap: () {
                                  Navigator.pop(context);
                                },
                                child: Container(
                                  padding: EdgeInsets.only(
                                      left: 40.w,
                                      right: 40.w,
                                      top: 20.w,
                                      bottom: 20.w),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                    // borderRadius:
                                    //     BorderRadius.all(Radius.circular(20.w)),
                                    image: DecorationImage(
                                      image: AssetImage(
                                          "assets/images/icon_update_btn.png"),
                                      fit: BoxFit.fill,
                                    ),
                                  ),
                                  child: Text(
                                    currentLanguage == "zh" ? "取消" : "Cancel",
                                    style: TextStyle(
                                      fontSize: 28.sp,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                      decoration: TextDecoration.none,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          );
        });
      },
    );
  }

  //获取周几
  String getWeekDay() {
    DateTime now = DateTime.now(); // 获取当前日期和时间
    String weekDay;
    if (currentLanguage == "zh") {
      switch (now.weekday) {
        case DateTime.monday:
          weekDay = "星期一";
          break;
        case DateTime.tuesday:
          weekDay = "星期二";
          break;
        case DateTime.wednesday:
          weekDay = "星期三";
          break;
        case DateTime.thursday:
          weekDay = "星期四";
          break;
        case DateTime.friday:
          weekDay = "星期五";
          break;
        case DateTime.saturday:
          weekDay = "星期六";
          break;
        default:
          weekDay = "星期天";
          break;
      }
    } else {
      switch (now.weekday) {
        case DateTime.monday:
          weekDay = "Monday";
          break;
        case DateTime.tuesday:
          weekDay = "Tuesday";
          break;
        case DateTime.wednesday:
          weekDay = "Wednesday";
          break;
        case DateTime.thursday:
          weekDay = "Thursday";
          break;
        case DateTime.friday:
          weekDay = "Friday";
          break;
        case DateTime.saturday:
          weekDay = "Saturday";
          break;
        default:
          weekDay = "Sunday";
          break;
      }
    }

    return weekDay;
  }
}
